/**
 *
 */
package com.longrise.android.byjk.plugins.login;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.common.Control;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.plugins.main.MainActivity;
import com.longrise.android.byjk.utils.CheckCard;
import com.longrise.android.byjk.utils.PhoneUtils;
import com.longrise.android.byjk.widget.view.InputBoxView;
import com.longrise.common.base.BaseActivity;
import com.longrise.common.datasource.local.sp.CacheUtils;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.ActivityUtil;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.utils.DZZWTools;

import java.text.ParseException;

/**
 * 注册页面
 * <p>
 * <p>
 * detailed comment
 *
 * @author callxkj 2015-12-28
 * @see
 * @since 1.0
 */
public class RegisterActivity extends BaseActivity implements OnClickListener,
        TextWatcher, CompoundButton.OnCheckedChangeListener, View.OnFocusChangeListener {
    protected static final String TAG = "RegisterActivity";
    private Button mBt;
    private InputBoxView mBv_zjlx;
    private InputBoxView mBv_zjhm;
    private InputBoxView mBv_dlmm;
    private InputBoxView mBv_qrmm;
    private InputBoxView mBv_name;
    private InputBoxView mBv_phoneNumber;
    private String username;
    private String signpwd_qr;
    private String mUsersfzh;
    private Toolbar mToolbar;
    private CheckBox mCheckBox;
    private TextView mTvprotocol;

    /*
     * private ImputBoxView mBv_ssdq;
     * 
     * private ImputBoxView mBv_gsmc;
     * 
     * private ImputBoxView mBv_cylx;
     */

    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_register;
    }

    @Override
    public void initView() {
        mToolbar = (Toolbar) findViewById(R.id.byjk_toolbar);
        mToolbar.setTitle(AppUtil.getString(R.string.yhzc));
        setSupportActionBar(mToolbar);

        mBt = (Button) findViewById(R.id.register_bt);
        // 证件类型
        mBv_zjlx = (InputBoxView) findViewById(R.id.register_zjlx);
        // 证件号码
        mBv_zjhm = (InputBoxView) findViewById(R.id.register_zjhm);
        // 登录密码
        mBv_dlmm = (InputBoxView) findViewById(R.id.register_dlmm);
        // 确认密码
        mBv_qrmm = (InputBoxView) findViewById(R.id.register_qrmm);
        // 姓名
        mBv_name = (InputBoxView) findViewById(R.id.register_name);
        // 手机号码
        mBv_phoneNumber = (InputBoxView) findViewById(R.id.register_phoneNumber);
        // 从业类型
        // mBv_cylx = (ImputBoxView) findViewById(R.id.register_cylx);
        // 所属地区
        // mBv_ssdq = (ImputBoxView) findViewById(R.id.register_ssdq);
        // 公司名称
        // mBv_gsmc = (ImputBoxView) findViewById(R.id.register_gsmc);

        //是否同意的checkbox
        mCheckBox = (CheckBox) findViewById(R.id.register_checkbox);
        mCheckBox.setChecked(true);
        //协议
        mTvprotocol = (TextView) findViewById(R.id.register_protocol_tv);
        mBt.setEnabled(false);
        EditText et_name = mBv_name.getEditText();
        initNameEt(et_name);


        initData();
        regEvent(true);
    }

    /**
     * 姓名输入框只能输入汉字 并且少于15个汉字
     */
    private void initNameEt(EditText et_name) {
        et_name.setInputType(InputType.TYPE_CLASS_TEXT);
        et_name.setFilters(new InputFilter[]{
                new InputFilter() {
                    @Override
                    public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                                               int dstart, int dend) {
                        String dests = dest.toString(); //已经显示的字符串
                        int destslen = 0;
                        if (!TextUtils.isEmpty(dests)) {
                            destslen = dests.length();
                        }
                        String s = dest.toString() + source;
                        if (destslen >= 15) {  //已经显示的字符串长度如果大于15 则不能输入
                            return "";
                        } else {
                            if ((s.length() <= 15) && (source.toString().matches("[\u4e00-\u9fa5]+"))) { //要输入的字符串长度+已经显示的字符串长度<=15
                                return source;
                            } else {
                                if ((!TextUtils.isEmpty(source)) &&
                                        (source.toString().matches("[\u4e00-\u9fa5]+"))) {
                                    String inputs = source.toString().substring(0, 15 - destslen);
                                    return inputs;
                                }
                            }
                        }
                        return "";
                    }
                }
        });

    }

    private void initData() {
        // 证件类型只有一个"身份证"
        EditText et_zjlx = mBv_zjlx.getEditText();
        et_zjlx.setText("证件类型 : 身份证");
        et_zjlx.setKeyListener(null);

        EditText etzjhm = mBv_zjhm.getEditText();

        // 登录密码
        mBv_dlmm.setRightClickMode(InputBoxView.PASSWORD);
        mBv_dlmm.setTextMode(InputBoxView.PASSWORD);
        // 确认密码
        mBv_qrmm.setRightClickMode(InputBoxView.PASSWORD);
        mBv_qrmm.setTextMode(InputBoxView.PASSWORD);

    }

    private void regEvent(boolean b) {
        if (mBt != null) {
            mBt.setOnClickListener(b ? this : null);
        }
        if (mBv_zjhm != null) {
            mBv_zjhm.setRightClickMode(InputBoxView.USERIF);
        }
        mBv_zjhm.getEditText().addTextChangedListener(this);//证件号码
        mBv_dlmm.getEditText().addTextChangedListener(this);//登录密码
        mBv_qrmm.getEditText().addTextChangedListener(this); //确认密码
        mBv_name.getEditText().addTextChangedListener(this); //姓名
        mBv_phoneNumber.getEditText().addTextChangedListener(this); //手机号码
        mBv_phoneNumber.setRightClickMode(InputBoxView.USERIF);
        mTvprotocol.setOnClickListener(this);
        mCheckBox.setOnCheckedChangeListener(this);
        mBv_zjhm.getEditText().setOnFocusChangeListener(this);
        mBv_name.setRightClickMode(InputBoxView.USERIF);
        mToolbar.setNavigationOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.register_bt:
                toRegist();
                /*
                 * ActionSheetDialog builder = new ActionSheetDialog(
                 * RegisterActivity.this).builder(); for (int x = 1; x < 100;
                 * x++) { builder.addSheetItem("条目" + x, SheetItemColor.Blue,
                 * new OnSheetItemClickListener() {
                 * 
                 * @Override public void onClick(int which) {
                 * Toast.makeText(RegisterActivity.this, "item" + which,
                 * Toast.LENGTH_SHORT) .show(); } }); }
                 * builder.setTitle("请选择省份").setCancelable(false)
                 * .setCanceledOnTouchOutside(false).show();
                 */
                break;
            case R.id.register_protocol_tv://保宝用户注册协议
                startActivity(UserAgreementActivity.class);
                break;
            default:
                break;
        }

    }

    /**
     * 注册
     */
    public void toRegist() {
        // 身份证号码
        mUsersfzh = mBv_zjhm.getText();
        if (mUsersfzh == null || mUsersfzh.equals("")) {
            DZZWTools.showToast(RegisterActivity.this, "证件号码不能为空", 0);
            return;
        }

        try {
            if (!CheckCard.IDCardValidate(mUsersfzh)) { //身份证号码有误
                DZZWTools.showToast(RegisterActivity.this, "证件号码格式错误", 0);
                return;
            }
        } catch (ParseException e1) {
            e1.printStackTrace();
        }


        final String signpwd = mBv_dlmm.getText();
        if (signpwd == null || signpwd.equals("")) {
            DZZWTools.showToast(RegisterActivity.this, "密码不能为空", 0);
            return;
        }

//        if("888888".equals(signpwd)){
//            DZZWTools.showToast(RegisterActivity.this, "您的密码过于简单，请设置字母加数字或下划线的混合密码", 0);
//            return;
//        }

        if (!signpwd.matches("[0-9a-z-A-Z_]{6,18}")) {
            DZZWTools.showToast(RegisterActivity.this, "密码只能包含字母、数字和下划线，6-18位", 0);
            return;
        }

        signpwd_qr = mBv_qrmm.getText();

        if (TextUtils.isEmpty(signpwd_qr)) {
            DZZWTools.showToast(RegisterActivity.this, "请输入确认密码", 0);
            return;
        }
        if (!signpwd.equals(signpwd_qr)) {
            DZZWTools.showToast(RegisterActivity.this, "两次输入密码不一致", 0);
            return;
        }

        username = mBv_name.getText();
        if (username == null || username.equals("")) {
            DZZWTools.showToast(RegisterActivity.this, "姓名不能为空", 0);
            return;
        }

        String userphone = mBv_phoneNumber.getText();

        if (userphone == null || userphone.equals("")) {
            DZZWTools.showToast(RegisterActivity.this, "手机号码不能为空", 0);
            return;
        }
        if (!PhoneUtils.isPhoneNumber(userphone)) { // 判断是否是电话号码
            DZZWTools.showToast(RegisterActivity.this, "手机号码格式错误", 0);
            return;
        }

        EntityBean bean = new EntityBean();
        bean.set("usersfzh", mUsersfzh);
        bean.set("signpwd", signpwd);
        bean.set("username", username);
        bean.set("userphone", userphone);
        final EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        DZZWTools.showWaitDialog(this);
        mBt.setClickable(false);
        UserController.getInstance().regist(this, fbean, new UserCallback() {
            @Override
            public void onSuccess(int status, String des) {
                //将用户名保存本地 方便下次进入软件时 自动填写
                CacheUtils.setString(Control.USERNAME, mUsersfzh);
                DZZWTools.showToast(RegisterActivity.this, des, 2 * 1000);
                if (status == UserCallback.HOME_PAGE) {
                    RegisterActivity.this.startActivity(new Intent(RegisterActivity.this, MainActivity.class));
                    ActivityUtil.finishAllAcivity();
                }
            }

            @Override
            public void onFail(String des) {
                DZZWTools.showToast(RegisterActivity.this, des, 2 * 1000);
            }

            @Override
            public void onFinish() {
                DZZWTools.dismissDialog(null);
                if (mBt != null) {
                    mBt.setClickable(true);
                }
            }
        });

    }

    /**
     * 判断身份证号是否存在
     * @param usersfzh 身份证号
     */
    private void toCheckCard(String usersfzh){
        if (TextUtils.isEmpty(usersfzh)) {
            DZZWTools.showToast(RegisterActivity.this, "证件号码不能为空", 0);
            return;
        }
        try {
            if (!CheckCard.IDCardValidate(usersfzh)) { //身份证号码有误
                DZZWTools.showToast(RegisterActivity.this, "证件号码格式错误", 0);
                return;
            }
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
        EntityBean bean = new EntityBean();
        bean.set("usersfzh",usersfzh);
        EntityBean fbean = new EntityBean();
        fbean.set("bean",bean);
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl, "bbt_login_isUserCardExit"
                , fbean, new LoadDataManager.OnRequestCallListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
               try{
                   EntityBean bean = (EntityBean) result;
                   String resultdesc = (String) bean.get("resultdesc");
                   int resultstate = (Integer) bean.get("resultstate");
                   if(resultstate!=1){
                       showToast(resultdesc);
                   }
               }catch (Exception e){

               }
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished(String key, String service) {

            }
        });
    }

    /**
     * @see android.app.Activity#onDestroy()
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        regEvent(false);
        mBt = null;
        mBv_zjlx = null;
        mBv_zjhm = null;
        mBv_dlmm = null;
        mBv_qrmm = null;
        mBv_name = null;
        mBv_phoneNumber = null;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        setConfrimBtStatus();
    }

    //-------checkbox----------
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        setConfrimBtStatus();
    }

    /**
     * 确定按钮是否为可点击
     */
    private void setConfrimBtStatus() {
        boolean b = checkText();
        boolean c = mCheckBox.isChecked();
        if (b && c) {
           mBt.setEnabled(true);
        } else {
           mBt.setEnabled(false);
        }
    }


    /**
     * 检查是否全部text有填写
     *
     * @return 全部填写返回true
     */
    private boolean checkText() {
        mUsersfzh = mBv_zjhm.getText();
        if (TextUtils.isEmpty(mUsersfzh)) {
            return false;
        }

        String signpwd = mBv_dlmm.getText();
        if (TextUtils.isEmpty(signpwd)) {
            return false;
        }

        signpwd_qr = mBv_qrmm.getText();
        if (TextUtils.isEmpty(signpwd_qr)) {
            return false;
        }

        username = mBv_name.getText();
        if (TextUtils.isEmpty(username)) {
            return false;
        }

        String userphone = mBv_phoneNumber.getText();
        if (TextUtils.isEmpty(userphone)) {
            return false;
        }

        return true;
    }

    //---------- 身份证焦点变化 ----------
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
            String sfzh = mBv_zjhm.getText();
        if(!hasFocus){ //失去焦点
            toCheckCard(sfzh);
            mBv_zjhm.setRightIcVisible(false);
        }else{
            if(!TextUtils.isEmpty(sfzh))
            mBv_zjhm.setRightIcVisible(true);
        }
    }
    //---------------------------------
}
